package com.baiyu.common.utils.sms;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baiyu.common.utils.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class AliyunSms {
//    #地域节点
//    smsEndPoint:dysmsapi.aliyuncs.com
//#AccessKeyId
//    smsAccessKeyId:LTAI4FgBZ4dtRe7s9xvTcCgn
//#AccessKeySecret
//    smsAccessKeySecret:dUbuEk7RnfEgJOi27plEytOll6MerG
//#签名名称
//    smsSingName:智务通
//#注册短信模板
//    smsRegisterCode:SMS_189712327
//#找回密码短信模板
//    smsFindPasswordCode:SMS_182677404
    private static final String Domain = "dysmsapi.aliyuncs.com";
    private static final String User_Name = "wangguangling@1613076807789606.onaliyun.com";
    private static final String Access_Key_ID = "LTAI4FgBZ4dtRe7s9xvTcCgn";
    private static final String Access_Key_Secret = "dUbuEk7RnfEgJOi27plEytOll6MerG";
    private static final String SigName = "智务通";//签名名称
    private static final String MbCode = "SMS_182677404";//改密码
    private static final String MbCode2 = "SMS_189712327";//注册

    private String Template_Type_Verify = "0";        // 验证码
    private String Template_Type_Notice = "1";        // 短信通知
    private String Template_Type_Spread = "2";        // 推广短信
    private String Template_Type_Other = "3";        // 国际/港澳台消息

    private static CommonRequest getCommonRequest() {
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(Domain);
        request.setVersion("2017-05-25");
        return request;
    }

    private static CommonResponse getCommonResponse(CommonRequest request) {
        DefaultProfile profile = DefaultProfile.getProfile(User_Name, Access_Key_ID, Access_Key_Secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return response;
    }

    /*
        增加短信模板
        type:    短信类型
        name:    模板名称
        content: 模板内容
        remark:  短信模板申请说明
     */
    public static JSONObject addSmsTemplate(String type, String name, String content, String remark) {
        CommonRequest request = getCommonRequest();
        request.setAction("AddSmsTemplate");
        request.putQueryParameter("TemplateType", type);
        request.putQueryParameter("TemplateName", name);
        request.putQueryParameter("TemplateContent", content);
        request.putQueryParameter("Remark", remark);

        CommonResponse response = getCommonResponse(request);
        if (response != null) {
            return JSONObject.parseObject(response.getData());
        }

		/*
        {
			"Code": "OK",
			"Message": "OK",
			"RequestId": "",
			"TemplateCode": ""
		}
		 */

        return null;
    }

    /*
        修改未通过审核的短信模板
        code:    短信模板CODE
        type:    短信类型
        name:    模板名称
        content: 模板内容
        remark:  短信模板申请说明
     */
    public static JSONObject modifySmsTemplate(String code, String type, String name, String content, String remark) {
        CommonRequest request = getCommonRequest();
        request.setAction("ModifySmsTemplate");
        request.putQueryParameter("TemplateCode", code);
        request.putQueryParameter("TemplateType", type);
        request.putQueryParameter("TemplateName", name);
        request.putQueryParameter("TemplateContent", content);
        request.putQueryParameter("Remark", remark);

        CommonResponse response = getCommonResponse(request);
        if (response != null) {
            return JSONObject.parseObject(response.getData());
        }

		/*
		{
			"Code": "OK",
			"Message": "OK",
			"RequestId": "",
			"TemplateCode": ""
		}
		 */

        return null;
    }

    /*
        删除短信模板
        code:	短信模板CODE
     */
    public static JSONObject deleteSmsTemplate(String code) {
        CommonRequest request = getCommonRequest();
        request.setAction("DeleteSmsTemplate");
        request.putQueryParameter("TemplateCode", code);

        CommonResponse response = getCommonResponse(request);
        if (response != null) {
            return JSONObject.parseObject(response.getData());
        }

		/*
		{
			"Code": "OK",
			"Message": "OK",
			"RequestId": "",
			"TemplateCode": ""
		}
		 */

        return null;
    }

    /*
        查询短信模板的审核状态
        code:	短信模板CODE
     */
    public static JSONObject querySmsTemplate(String code) {
        CommonRequest request = getCommonRequest();
        request.setAction("QuerySmsTemplate");
        request.putQueryParameter("TemplateCode", code);

        CommonResponse response = getCommonResponse(request);
        if (response != null) {
            return JSONObject.parseObject(response.getData());
        }

		/*
		{
			"Code": "OK",
			"Message": "OK",
			"RequestId": "",
			"TemplateCode": "",
			"TemplateType": 1,
			"TemplateContent": "",
			"TemplateName": "",
			"CreateDate": "2019-06-04 11:42:17",
			"TemplateStatus": 1,
			"Reason": ""
		}
		 */

        return null;
    }


    /*
        查看短信发送记录和发送状态
        page:   发送记录的的当前页码
        size:   每页显示短信数量, 1~50
        number: 接收手机号码
        date:   发送日期 20181228
     */
    public static JSONObject querySendDetails(String page, String size, String number, String date) {
        return querySendDetails(page, size, number, date, null);
    }

    /*
        查看短信发送记录和发送状态
        page:   发送记录的的当前页码
        size:   每页显示短信数量, 1~50
        number: 接收手机号码
        date:   发送日期 20181228
        id:     发送流水号
     */
    public static JSONObject querySendDetails(String page, String size, String number, String date, String id) {
        CommonRequest request = getCommonRequest();
        request.setAction("QuerySendDetails");
        request.putQueryParameter("CurrentPage", page);
        request.putQueryParameter("PageSize", size);
        request.putQueryParameter("PhoneNumber", number);
        request.putQueryParameter("SendDate", date);
        if (StringUtils.isNotEmpty(id)) {
            request.putQueryParameter("BizId", id);
        }

        CommonResponse response = getCommonResponse(request);
        if (response != null) {
            return JSONObject.parseObject(response.getData());
        }

		/*
		{
			"Code": "OK",
			"Message": "OK",
			"RequestId": "",
			"TotalCount": 1,
			"SmsSendDetailDTOs": {
				"SmsSendDetailDTO": [ {
					"SendDate": "",
					"OutId": "",			// 外部流水扩展字段
					"SendStatus": 3,		// 1：等待回执, 2：发送失败, 3：发送成功
					"ReceiveDate": "",
					"ErrCode": "DELIVRD",	// DELIVRD: 短信发送成功, 其他值：短信发送失败
					"TemplateCode": "",
					"Content": "",
					"PhoneNum": ""
					},
					...
				]
			},
		}
		 */

        return null;
    }


    /*
        增加短信签名，并重新提交审核
        name:   签名名称
        source: 签名来源, 0：企事业单位的全称或简称 1：工信部备案网站的全称或简称 2：APP应用的全称或简称 3：公众号或小程序的全称或简称 4：电商平台店铺名的全称或简称 5：商标名的全称或简称
        remark: 短信签名申请说明
        parameter: 扩展参数
            SignFileList.N.FileSuffix:		签名证明文件格式，支持jpg、png、gif或jpeg格式
            SignFileList.N.FileContents:	签名的资质证明文件经base64编码后的字符串
     */
    public static JSONObject addSmsSign(String name, String source, String remark, Map<String, String> parameter) {
        CommonRequest request = getCommonRequest();
        request.setAction("AddSmsSign");
        request.putQueryParameter("SignName", name);
        request.putQueryParameter("SignSource", source);
        request.putQueryParameter("Remark", remark);
        // 企业用户必须填写此参数
        if (parameter != null) {
            if (parameter.containsKey("SignFileList.N.FileSuffix")){
                request.putQueryParameter("SignFileList.N.FileSuffix", parameter.get("SignFileList.N.FileSuffix"));        // "jpg"
                 }
            if (parameter.containsKey("SignFileList.N.FileContents")){
                request.putQueryParameter("SignFileList.N.FileContents", parameter.get("SignFileList.N.FileContents")); // base64编码, 不超过2MB
            }
        }

        CommonResponse response = getCommonResponse(request);
        if (response != null) {
            return JSONObject.parseObject(response.getData());
        }

		/*
		{
			"Code": "OK",
			"Message": "OK",
			"RequestId": "",
			"SignName": ""
		}
		 */

        return null;
    }

    /*
        修改未审核通过的短信签名，并重新提交审核
        name:   签名名称
        source: 签名来源, 0：企事业单位的全称或简称 1：工信部备案网站的全称或简称 2：APP应用的全称或简称 3：公众号或小程序的全称或简称 4：电商平台店铺名的全称或简称 5：商标名的全称或简称
        remark: 短信签名申请说明
        parameter: 扩展参数
     */
    public static JSONObject modifySmsSign(String name, String source, String remark, Map<String, String> parameter) {
        CommonRequest request = getCommonRequest();
        request.setAction("ModifySmsSign");
        request.putQueryParameter("SignName", name);
        request.putQueryParameter("SignSource", source);
        request.putQueryParameter("Remark", remark);

        if (parameter != null) {
            if (parameter.containsKey("SignFileList.N.FileSuffix")){
                request.putQueryParameter("SignFileList.N.FileSuffix", parameter.get("SignFileList.N.FileSuffix"));        // "jpg"
            }
            if (parameter.containsKey("SignFileList.N.FileContents")){
                request.putQueryParameter("SignFileList.N.FileContents", parameter.get("SignFileList.N.FileContents")); // base64编码, 不超过2MB
            }
        }

        CommonResponse response = getCommonResponse(request);
        if (response != null) {
            return JSONObject.parseObject(response.getData());
        }

		/*
		{
			"Code": "OK",
			"Message": "OK",
			"RequestId": "",
			"SignName": ""
		}
		 */

        return null;
    }

    /*
        删除短信签名申请状态
        name: 签名名称
     */
    public static JSONObject deleteSmsSign(String name) {
        CommonRequest request = getCommonRequest();
        request.setAction("DeleteSmsSign");
        request.putQueryParameter("SignName", name);

        CommonResponse response = getCommonResponse(request);
        if (response != null) {
            return JSONObject.parseObject(response.getData());
        }

		/*
		{
			"Code": "OK",
			"Message": "OK",
			"RequestId": "",
			"SignName": ""
		}
		 */

        return null;
    }

    /*
        查询短信签名申请状态
        name: 签名名称
     */
    public static JSONObject querySmsSign(String name) {
        CommonRequest request = getCommonRequest();
        request.setAction("QuerySmsSign");
        request.putQueryParameter("SignName", name);

        CommonResponse response = getCommonResponse(request);
        if (response != null) {
            return JSONObject.parseObject(response.getData());
        }

		/*
		{
			"Code": "OK",
			"Message": "OK",
			"RequestId": "",
			"SignName": "",
			"CreateDate": "",
			"Reason": "",
			"SignStatus": 1
		}
		 */

        return null;
    }


    /*
        发送短信
        numbers:   手机号码, "15900000000,13500000000"
        name:      签名名称, "阿里云"
        code:      短信模板
        parameter: 扩展参数
     */
    public static JSONObject sendSms(String numbers, String name, String code, Map<String, String> parameter) {
        CommonRequest request = getCommonRequest();
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", numbers);
        request.putQueryParameter("SignName", name);
        request.putQueryParameter("TemplateCode", code);
        if (parameter != null) {
            if (parameter.containsKey("OutId")) {
                request.putQueryParameter("OutId", parameter.get("OutId"));
            }
            if (parameter.containsKey("SmsUpExtendCode")) {
                request.putQueryParameter("SmsUpExtendCode", parameter.get("SmsUpExtendCode"));
            }
            if (parameter.containsKey("TemplateParam")) {
                request.putQueryParameter("TemplateParam", parameter.get("TemplateParam"));  // {"code":"1111"}
            }
        }
        CommonResponse response = getCommonResponse(request);
        if (response != null) {
            return JSONObject.parseObject(response.getData());
        }
        return null;
    }

    /*
        批量发送短信
        numbers:   手机号码, ["15900000000","13500000000"]
        name:      签名名称, ["阿里云","阿里巴巴"]
        code:      短信模板
        parameter: 扩展参数
     */
    public static JSONObject sendBatchSms(String numbers, String name, String code, Map<String, String> parameter) {
        CommonRequest request = getCommonRequest();
        request.setAction("SendBatchSms");
        request.putQueryParameter("PhoneNumberJson", numbers);
        request.putQueryParameter("SignNameJson", name);
        request.putQueryParameter("TemplateCode", code);
        if (parameter != null) {
            if (parameter.containsKey("SmsUpExtendCodeJson")) {
                request.putQueryParameter("SmsUpExtendCodeJson", parameter.get("SmsUpExtendCodeJson"));
            }
            if (parameter.containsKey("TemplateParamJson")) {
                request.putQueryParameter("TemplateParamJson", parameter.get("TemplateParamJson"));  // [{"name":"TemplateParamJson"},{"name":"TemplateParamJson"}]
            }
        }
        CommonResponse response = getCommonResponse(request);
        if (response != null) {
            return JSONObject.parseObject(response.getData());
        }
        return null;
    }

    /*
        发送短信验证码
        number: 手机号码
        name:   签名名称
        code:   短信模板
     */
    public static JSONObject sendVerifySms(String number, Map<String, String> parameter,int code) {
        JSONObject result = new JSONObject();
        Date date = Calendar.getInstance().getTime();
        String dateStr = new SimpleDateFormat("yyyyMMdd").format(date);
        JSONObject json = null;
        if(code==1){
            json= sendSms(number, SigName, MbCode, parameter);
        }else if(code==3){
            json= sendSms(number, SigName, MbCode2, parameter);
        }
        if (StringUtils.isNotNull(json)) {
            if ("OK".equalsIgnoreCase(json.getString("Code"))) {
                String bizid = json.getString("BizId");
                JSONObject detail = querySendDetails("1", "5", number, dateStr, bizid);
                if (StringUtils.isNotNull(detail) && "OK".equalsIgnoreCase(detail.getString("Code"))) {
                    JSONArray list = detail.getJSONObject("SmsSendDetailDTOs").getJSONArray("SmsSendDetailDTO");
                    result.put("code", "OK");
                    result.put("msg", "OK");
                    if (list.size() > 0) {
                        result.put("value", list.getJSONObject(0).getString("OutId"));
                    }
                    return result;
                } else {
                    result.put("code", "ERROR");
                    result.put("msg", "短信状态查询失败！");
                }
            } else {
                result.put("code", "ERROR");
                result.put("msg", "短信发送失败！");
            }
        } else {
            result.put("code", "ERROR");
            result.put("msg", "短信发送失败！");
        }

        return result;
    }

    /**
     * 调用卫健委发送短信功能接口
     * @param map 参数
     * @return json字符串
     */
    //public static AjaxResult sendPhoneSms(Map<String, Object> map){
    //
    //}
    //
    //public static void main(String[] str){
    //    Map<String, Object> map = new HashMap<>();
    //    sendPhoneSms(map);
    //}

}
